<template>
  <div class="import-team-order">
    <el-dialog
      v-el-drag-dialog="{ drag: true, full: false, resize: false }"
      :visible="true"
      :close-on-click-modal="false"
      @close="closeMd"
      :append-to-body="true"
      :title="`导入订单`"
      width="450px">
      <el-form 
        :model="fm.ps" 
        :ref="fm.fname"
        @keyup.enter.native="onSubmit" 
        :label-width="'100px'">
        <el-form-item 
          ref="exUploadItem"
          label="导入文件" 
          prop="expFile"
          required
          :rules="[{ required: true, message: '导入Excel文件不能为空', trigger: 'change'}]">
          <el-upload
            ref="exUpload"
            :limit="1"
            :multiple="false"
            accept=".xls,.xlsx"
            action="#"
            :http-request="onUploadFile"
            :on-remove="onRemoveFile">
            <div>
              <el-button size="small" type="primary">点击上传</el-button>
              <span class="c-yellow">（只能上传.xls/.xlsx的Excel文件）</span>
            </div>
            <div slot="tip" class="c-red">{{errMsg}}</div>
          </el-upload>
        </el-form-item>

        <el-form-item 
          label="用车单位" 
          prop="cusUname" 
          :rules="[{required: false, message: '用车单位不能为空'}]">
          <el-select 
            v-model="fm.ps.cusUname" 
            clearable filterable 
            :remote="true"
            :remote-method="queryCusPageList"
            :placeholder="'请搜索选择用车单位'"
            style="width: 100%">
            <el-option
                v-for="it in clientList"
                :key="it.baseUserId.uname"
                :label="it.baseUserId.realName+'【' +it.baseUserId.phone+ '】【'+ it.unitName +'】'"
                :value="it.baseUserId.uname">
                <span>{{ it.baseUserId.realName }}</span>
                <span>{{ '【' +it.baseUserId.phone+ '】【'+ it.unitName +'】' }}</span>
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button 
          type="warning" 
          :icon="'el-icon-download'" 
          @click="downExcelTemplate">
          下载导入Excel模板
        </el-button>

        <el-button 
          type="primary" 
          :icon="'el-icon-qimport'" 
          @click="onSubmit" 
          :loading="fm.sb.load">
          确认导入
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog';

import { downFiles } from "@/api/export";
import * as commService from '@/api/services/common.service';
import * as orderSer from '@/api/services/order.service';

export default {
  name: 'ImportTeamOrder',
  directives: { elDragDialog },
  data() {
    return {
      fm: {// 表单数据对象
        fname: "importTeamOrderFm",
        sb: { load: false },

        // 提交参数对象
        fd: new FormData(),

        // 参数对象
        ps: {
          // 导入的文件
          expFile: null,
          // 用车单位
          cusUname: null,
        },
        // 上传文件错误提示
        errMsg: '',
      },

      // 客户数据列表
      clientList: [],  

    }
  },
  computed: {
    // 操作错误信息
    errMsg: function(){
      return this.fm.errMsg;
    },
  },
  methods:{
    closeMd() {
      this.$emit("myClick", {state: false});
    },
    // 下载导入Excel模板
    downExcelTemplate(){
      const that = this, U = that.U;

      U.qconfim('确定下载车队订单导入Excel模板吗？').then(r => {
        if(r){
          orderSer.downImportTeamOrderExcelModel().then(res => {
            downFiles(res, '车队订单导入模板');
          });
        }
      });
    },

    /**
     * 获取-单位客户列表（用于下拉框）
     * @param find 客户手机号/用户名
     */
    queryCusPageList(find){
      const that = this;

      commService.queryComboCusPageList({page: 1, rows: 20, find: find}).then(res=> {
        if(res && res.code == 1) that.clientList = res.data;
      });
    },

    // 覆盖默认上传行为
    onUploadFile(params){
      // 保存文件对象至表单对象中
      this.fm.ps.expFile = params.file;
      // 清空错误提示
      this.$refs.exUploadItem.clearValidate();
    },

    // 移除列表项事件
    onRemoveFile(file, fileList){
      // 保存文件对象至表单对象中
      this.fm.ps.expFile = null;
    },

    // 提交表单
    onSubmit() {
      let that = this, U = that.U, fm = that.fm, sb = fm.sb;

      that.$refs[fm.fname].validate((valid) => {
        if (!valid) { return false; } else {
          if(!fm.ps.expFile){
            U.qerror('请选择导入的Excel文件');
          }else{
            sb.load = true;

            let fd = new FormData();
            fd.append('companyOrdersFile', fm.ps.expFile);
            if(fm.ps.cusUname){
              fd.append('cusUname', fm.ps.cusUname);
            }

            orderSer.importCompanyOrder(fd).then(res => {
              sb.load = false;

              if(res.code != 1){
                U.qerror(res.msg);
              }else{
                U.qsuccess(res.msg);

                // 移除文件列表
                that.onRemoveFile();

                // 刷新列表
                that.$emit("reloadDg");

                that.closeMd();
              }
            });
          }

          setTimeout(() => { sb.load = false; }, 10000);
        }
      });
    },
    
  },
 }
</script>
